package com.weixin.paleituo.view;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.LoginActivity;
import com.weixin.paleituo.adapter.UseMyHomeSelectGoodsRecycleAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.ActivityLifeCycleEvent;
import com.weixin.paleituo.bean.GoodsSelectBean;
import com.weixin.paleituo.bean.SelectAttrBean;
import com.weixin.paleituo.bean.SpecificationListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.eventbus.UseMyHomeSureEvent;
import com.weixin.paleituo.help.TextWatcherImp;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;

/**
 * Author yichao
 * Time  2017/12/10 20:06
 * Dest  应用选择商品属性
 */
public class SelectGoodsAttriUseMyHomePopuWindow extends PopupWindow {

    private View rootView;
    private Context context;
    private PublishSubject<ActivityLifeCycleEvent> mLifecycleSubject;
    private RecyclerView mRecyclerView;
    private ImageView mIvDelete;
    private List<SpecificationListBean> mSpecificationList=new ArrayList<>();
    private UseMyHomeSelectGoodsRecycleAdapter mUseMyHomeSelectGoodsRecycleAdapter;
    private ImageView mIvicon;
    private TextView mTvSelectNumber;
    private TextView mTvSelectAttr;
    private TextView mTvMoney;
    private int mGoodsId;
    private Dialog mLoadingDialog;
    private TextView mTvSure;
    private String mLastName;
    private double mStorePrice;
    private int mNumber;
    private int mCustomized;
    private HeaderAndFooterWrapper mHeaderAndFooterWrapper;
    private View mFootView;
    private LinearLayout mLlcustomserviceRoot;
    private Button mButton ;
    private EditText mEditText;
    boolean   isvisible=false;
    private String TAG="SelectGoodsAttriPopuWindow";
    private double mCoupon;
    private String mIconUrl;
    private String mGoodsName;
    private String mStoreId;
    private double mVipPrice;
    private boolean mIsvip;
    private String mIdList="";//选中的规格属性
    private ImageView mVipImageView;
    private NumberButton mNumberButton;
    private int[] mSelectIdArr;
    private int mPostion;

    public SelectGoodsAttriUseMyHomePopuWindow(Context context, PublishSubject<ActivityLifeCycleEvent> lifecycleSubject) {
        super(context);
        this.context = context;
        mLifecycleSubject = lifecycleSubject;
        init();
    }

    private void init() {
        rootView = LayoutInflater.from(context).inflate(R.layout.select_goods_attr_popuwindow_layout, null);
        mIvicon=  rootView.findViewById(R.id.iv_icon_select_goods_attr_popuwindow_layout);
        mIvDelete  = rootView.findViewById(R.id.iv_delete_select_goods_attr_popuwindow_layout);
        mTvSelectNumber = rootView.findViewById(R.id.tv_select_number_select_goods_attr_popuwindow_layout);
        mTvSelectAttr = rootView.findViewById(R.id.tv_selected_attr_select_goods_attr_popuwindow_layout);
        mTvMoney = rootView.findViewById(R.id.tv_monety_select_goods_attr_popuwindow_layout);
        mTvSure = rootView.findViewById(R.id.tv_sure_select_goods_attr_popuwindow_layout);
        mVipImageView = rootView.findViewById(R.id.iv_vipicon_select_goods_attr_popuwindos_layout);
        mIvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        rootView.findViewById(R.id.view_select_goods_attr_popuwindow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mFootView = UIUtils.inflate(context, R.layout.layout_select_goods_attr_foot);

        mLlcustomserviceRoot = mFootView.findViewById(R.id.ll_customservice_root_layout_select_goods_attr_foot);
        mButton = mFootView.findViewById(R.id.rb_layout_select_goods_attr_foot);
        mEditText = mFootView.findViewById(R.id.et_custom_layout_select_goods_attr_foot);
        mButton.setSelected(false);

        mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (!BaseApplication.isLoginSuccess){
            LoginActivity.startActivity(context,true);
            return;
        }

        if (!isvisible){
            isvisible=true;
            mEditText.setVisibility(View.VISIBLE);
            mButton.setSelected(true);

            mUseMyHomeSelectGoodsRecycleAdapter.setVisible(true);
            //xianshi

        }else {
            isvisible=false;
            mButton.setSelected(false);
            mEditText.setVisibility(View.GONE);
            mUseMyHomeSelectGoodsRecycleAdapter.setVisible(false);
            //关闭

        }
        setCustomshow();
    }
});

        mEditText.addTextChangedListener(new TextWatcherImp() {
            @Override
            public void afterTextChanged(Editable s) {
                String s1 = s.toString();
                setCustomshow();
            }
        });

        mNumberButton = mFootView.findViewById(R.id.number_button);
        mNumberButton.setBuyMax(200)
                .setInventory(1000)
                .setCurrentNumber(1)
                .setOnWarnListener(new NumberButton.OnWarnListener() {

                    @Override
                    public void onWarningForInventory(int inventory) {
                        ToastUtils.makeText("当前库存:" + inventory);
                    }
                    @Override
                    public void onWarningForBuyMax(int buyMax) {
                        ToastUtils.makeText("超过最大购买数:" + buyMax);
                    }

                    @Override
                    public void number(int number) {
                        mNumber = number;
                        mTvSelectNumber.setText("数量    " + number);

                    }
                });
        // TODO: 2016/5/17 设置动画
       // setAnimationStyle(R.style.dialog);

        // TODO: 2016/5/17 设置背景颜色
      setBackgroundDrawable(new ColorDrawable(0x90000000));
        // TODO: 2016/5/17 设置可以获取焦点
      setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
      setOutsideTouchable(true);
        // TODO：更新popupwindow的状态
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(rootView);
        mRecyclerView = rootView.findViewById(R.id.recycle_select_goods_attr_popuwindow_layout);
        mUseMyHomeSelectGoodsRecycleAdapter = new UseMyHomeSelectGoodsRecycleAdapter(context,mSpecificationList);
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(mUseMyHomeSelectGoodsRecycleAdapter);
        mHeaderAndFooterWrapper.addFootView(mFootView);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        //设置adapter
        mRecyclerView.setAdapter(mHeaderAndFooterWrapper);
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
 /*   /*//*    mRecyclerView.addItemDecoration(new DividerItemDecoration(
                context, DividerItemDecoration.VERTICAL));*/
        mUseMyHomeSelectGoodsRecycleAdapter.setSelectAttrListener(new UseMyHomeSelectGoodsRecycleAdapter.SelectAttrListener() {



            @Override
            public void selectOnClick(String idList, int selectPosition, int position, int[] selectIdArr) {
                mSelectIdArr = selectIdArr;
                mIdList = idList;

                LogUtils.i(TAG,"selectPostiont::"+selectPosition +"_____position"+position);

                Observable observable = ApiUtils.getApi().getGoodsAttr(mGoodsId, idList, BaseApplication.getToken(),BaseApplication.getUserId())
                        .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(context, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SelectAttrBean>(context) {
                    @Override
                    protected void _onNext(StatusCode<SelectAttrBean> selectAttrBeanStatusCode) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        SelectAttrBean data = selectAttrBeanStatusCode.getData();
                        if (selectAttrBeanStatusCode.isFlag()&&data!=null){
                            mTvSure.setEnabled(true);
                            mTvSure.setFocusable(true);
                            mLastName = data.getLastName();
                            mStorePrice = data.getStorePrice();
                            mCustomized = data.getCustomized();
                            mVipPrice = data.getSpecialSales();
                            mCoupon = data.getCoupon();
                            mIconUrl=  data.getSummaryList();
                            UIUtils.loadImageView(context,mIconUrl,mIvicon);

                          //  mTvSelectNumber.setText("数量"+data.getSelectNumber());
                            String editConte = mEditText.getText().toString();
                            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
                            mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"":mLastName);
                            if (mIsvip&&!isvisible){
                                mVipImageView.setVisibility(View.VISIBLE);
                                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                                mTvMoney.setText("￥"+UIUtils.getMoney(mVipPrice));
                            }else {
                                mTvMoney.setText("￥"+UIUtils.getMoney(mStorePrice));
                                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
                                mVipImageView.setVisibility(View.INVISIBLE);
                            }
                        }else {
                            mTvSure.setEnabled(false);
                            mTvSure.setFocusable(false);
                            ToastUtils.makeText(selectAttrBeanStatusCode.getDetailMsg());
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        ToastUtils.makeText(message);
                        mTvSure.setEnabled(false);
                        mTvSure.setFocusable(false);

                    }
                },"",mLifecycleSubject,false,true);

            }
        });

        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

    if (!BaseApplication.isLoginSuccess){
    LoginActivity.startActivity(context,true);
        return;
    }
        String etContet = mEditText.getText().toString();
        boolean isAlreadyCustom;
    if (isvisible){
        //定制
        if (StringUtils.isEmpty(etContet)){
            ToastUtils.makeText("请输入您的定制服务需求");
            return;
        }else {
            isAlreadyCustom=true;
        }
    }else {
        isAlreadyCustom=false;
    }
         //确定
                UseMyHomeSureEvent useMyHomeSureEvent=new UseMyHomeSureEvent();
                useMyHomeSureEvent.setSelectIdArr(mSelectIdArr);
                useMyHomeSureEvent.setPostion(mPostion);
                useMyHomeSureEvent.setIsVip(mIsvip);
                useMyHomeSureEvent.setIsAlreadyCustom(isAlreadyCustom);
                useMyHomeSureEvent.setNumber(mNumber);
                useMyHomeSureEvent.setSelectInfo(mLastName);
                useMyHomeSureEvent.setImageUrl(mIconUrl);
                useMyHomeSureEvent.setCustomInfo(etContet);
                if (mIsvip){
                    useMyHomeSureEvent.setPrice(Double.toString(mStorePrice));
                    useMyHomeSureEvent.setSpecialSales(Double.toString(mVipPrice));
                }else {
                    useMyHomeSureEvent.setPrice(Double.toString(mStorePrice));
                }








                EventBus.getDefault().post(useMyHomeSureEvent);
                dismiss();



            }
        });
    }

    /**
     * 显示定制
     */
    private  void setCustomshow() {
        if (isvisible){
            mTvSure.setText("确定");
            mTvSelectAttr.setText("私人订制");
            mTvMoney.setText("待定");
            mVipImageView.setVisibility(View.INVISIBLE);
            mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
        }else {
            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
            if (mIsvip){
                mVipImageView.setVisibility(View.VISIBLE);
                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                mTvMoney.setText("￥"+ UIUtils.getMoney(mVipPrice));
            }else {
                mTvMoney.setText("￥"+ UIUtils.getMoney(mStorePrice));
                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
                mVipImageView.setVisibility(View.INVISIBLE);
            }
            mTvSure.setText("确定");
            mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"" :mLastName);
        }
    }

    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24){
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            setHeight(height);
        }
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if(Build.VERSION.SDK_INT >= 24){
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            setHeight(height);
        }
        super.showAsDropDown(anchor, xoff, yoff);
    }
    /**
     *
     * @param goodsSelectBean
     * @param goodsId
     */
    public void setGoodsSelectBean(GoodsSelectBean goodsSelectBean, int goodsId) {
        mGoodsId =goodsId;
        mIconUrl = goodsSelectBean.getSummary();
        mLastName=goodsSelectBean.getSelectedLastName();
        mStorePrice=goodsSelectBean.getStorePrice();
        mNumber=goodsSelectBean.getSelectNumber();
        mCoupon=goodsSelectBean.getCoupon();
        mGoodsName = goodsSelectBean.getGoodsName();
        mStoreId = goodsSelectBean.getStoreId();
        mVipPrice = goodsSelectBean.getVipPrice();
        mIsvip = goodsSelectBean.isVip();

        Glide.with(context).load(mIconUrl).into(mIvicon);
        mTvSelectNumber.setText("数量    "+goodsSelectBean.getSelectNumber());
        mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"":mLastName);
        mNumberButton.setCurrentNumber(goodsSelectBean.getSelectNumber());

    if (mIsvip){
    mVipImageView.setVisibility(View.VISIBLE);
    mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
    mTvMoney.setText("￥"+UIUtils.getMoney(goodsSelectBean.getVipPrice()));
}else {
    mTvMoney.setText("￥"+UIUtils.getMoney(goodsSelectBean.getStorePrice()));
    mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
    mVipImageView.setVisibility(View.INVISIBLE);

}

        String customMessage = goodsSelectBean.getCustomMessage();

        mEditText.setText(StringUtils.isEmpty(customMessage)?"":customMessage);


        mEditText.setSelection(StringUtils.isEmpty(customMessage)?0:customMessage.length());

    }
    /**
     * 设置属性
     * @param specificationList
     */
    public void setList(List<SpecificationListBean> specificationList) {
        mSpecificationList.clear();
        mSpecificationList.addAll(specificationList);
        if (specificationList!=null&& specificationList.size()>0){
            for (SpecificationListBean specificationListBean:specificationList){

                mIdList=mIdList+specificationListBean.getCheckId()+"_";

            }
        }

        mUseMyHomeSelectGoodsRecycleAdapter.setSelectArr();
    }

    /**
     * 刷新数据
     */
    public void refresh(){
        mUseMyHomeSelectGoodsRecycleAdapter.notifyDataSetChanged();

    }

    /**
     * 是否定制
     * @param customized  制1支持2不支持
     */
    public void setCustomized(int customized) {
        if (customized==1){
            mLlcustomserviceRoot.setVisibility(View.VISIBLE);
        }else {
            mLlcustomserviceRoot.setVisibility(View.GONE);
        }

        mCustomized = customized;
    }

    /**
     * 点击位置
     * @param postion
     */
    public void setPosition(int postion) {

        mPostion = postion;
    }
}
